import React, { ReactNode } from 'react';
import Storage from './storage';
import { Dropdown, Menu } from 'antd';
import { CaretDownOutlined } from '@ant-design/icons';

export const md5 = require('blueimp-md5');

export const storage = new Storage();
// 防抖
export const handleDebounce = (func: Function, delay: number, immediate: boolean = true) => {
    let timer: any;
    return function (this: unknown, ...args: any[]) {
        const that = this;
        if (immediate) {
            func.apply(that, args); // 确保引用函数的指向正确，并且函数的参数也不变
            immediate = false;
            return;
        }
        clearTimeout(timer);
        timer = setTimeout(() => {
            func.apply(that, args);
        }, delay);
    };
};

// 节流

// 按钮过多优化
export const renderMoreActions = (actionList: any[], length?: number) => {
    const actionListLength = length || 3;
    if (actionList.length <= actionListLength) {
        return actionList;
    }
    const moreActionList = actionList.splice(2, actionList.length - 2);
    const menu = (
        <Menu style={{ minWidth: 90 }}>
            {moreActionList.map((item, index) => {
                return <Menu.Item key={index.toString()}>{item}</Menu.Item>;
            })}
        </Menu>
    );
    return (
        <>
            {actionList}
            <Dropdown
                overlay={menu}
                trigger={['click']}
                placement="bottomRight"
                overlayClassName="irr__action__list--more"
            >
                <span className="irr_action_more--item" onClick={e => e.preventDefault()}>
                    更多 <CaretDownOutlined />
                </span>
            </Dropdown>
        </>
    );
};

// 小数点后保留两位
export const toDecimal2 = (x: any, index?: number) => {
    let f = parseFloat(x);
    if (isNaN(f)) {
        return false;
    }
    f = Math.round(x * 10000) / 10000;
    let s: any = f.toString();
    let rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + (index || 2)) {
        s += '0';
    }
    s = s.toString().match(/^\d+(?:\.\d{0,1})?/);
    return s;
};

// react插槽
export const findChild = (children: ReactNode, key: string, placeholder?: ReactNode): ReactNode => {
    let node: ReactNode = placeholder || null;
    if (Array.isArray(children)) {
        // @ts-ignore
        node = children.find(child => child.key === key);
    } else {
        //@ts-ignore
        if (children?.key === key) {
            node = children;
        }
    }
    return node;
};

export const buildTreeData = (
    treeData: any[],
    title: string,
    key: string,
    children: string,
    parentId: any,
    disableData?: any[],
    showIcon?: boolean | undefined
): any[] => {
    const result: {
        title: string;
        key: string;
        parentId: string;
        children: any[];
    }[] = [];
    treeData.map((item: any) => {
        let disabled = false;
        if (disableData?.includes(item[key])) {
            disabled = true;
        }
        const treeNodeData: any = {
            title: item[title],
            name: item[title],
            key: item[key],
            value: item[key],
            parentId: parentId,
            parentAreaId: parentId,
            selectable: item.permission,
            disabled,
            ...item
        };
        // if (showIcon && item.treeNodeType) {
        //     treeNodeData.icon = <img src={treeIconMap[item.treeNodeType]} />;
        // }
        //
        if (Array.isArray(item[children])) {
            treeNodeData.children = buildTreeData(
                item[children],
                title,
                key,
                children,
                item[key],
                disableData,
                showIcon
            );
        }
        result.push(treeNodeData);
    });
    return result;
};

/**
 * @description: 根据key值获取当前节点项
 */

export const getTreeNodeByKey = (treeData: any[], key: string | number, isKeyword: boolean, isFilter?: boolean) => {
    const flatTreeData: any = [];
    if (isFilter) {
        const treeNodes = flatTreeData.filter((item: any) => {
            if (typeof item.title === 'string') {
                if (isKeyword) {
                    //@ts-ignore
                    return item.title.indexOf(key) > -1;
                } else {
                    return item.key === key;
                }
            } else {
                if (isKeyword) {
                    //@ts-ignore
                    return item.name.indexOf(key) > -1;
                } else {
                    return item.key === key;
                }
            }
        });
        return treeNodes;
    }
    const treeNodeData = flatTreeData.find((item: any) => {
        if (typeof item.title === 'string') {
            if (isKeyword) {
                //@ts-ignore
                return item.title.indexOf(key) > -1;
            } else {
                return item.key === key;
            }
        } else {
            if (isKeyword) {
                //@ts-ignore
                return item.name.indexOf(key) > -1;
            } else {
                return item.key === key;
            }
        }
    });
    return treeNodeData;
};

//根据树节点数据获取扁平化数组
export const getFlatTreeData = (treeData: any[], result?: any[]) => {
    const treeResult = result || [];
    treeData.map((item: any) => {
        treeResult.push(item);
        if (Array.isArray(item.children) && item.children.length > 0) {
            getFlatTreeData(item.children, treeResult);
        }
    });
    return treeResult || [];
};

export const getSocketConf = (host: string, protocol: string) => {
    const uri = '/notification/v1.0.0/ws/';
    const appId = storage.getSession('appId');
    return {
        url: `${protocol === 'http:' ? 'ws://' : 'wss://'}${host}${uri}${appId}`
    };
};

// // 下载html为图片
// export const downHtmlToImg = (id: string, name: string, type: string) => {
//   const node: any = document.getElementById(id);
//   domtoimage.toBlob(node).then((blob: any) => {
//     saveAs(blob, `${name}.${type}`);
//   });
// };
// 获取地址栏参数

export const getQueryString = (name: any) => {
    let strHref = window.location.href;
    let intPos = strHref.indexOf('?');
    let strRight = strHref.substr(intPos + 1);
    let arrTmp = strRight.split('&');
    for (let i = 0; i < arrTmp.length; i++) {
        let arrTemp = arrTmp[i].split('=');
        if (arrTemp[0].toUpperCase() === name.toUpperCase()) return arrTemp[1];
    }
    return '';
};
